package herong.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharsetConversion implements Filter {
	
	protected FilterConfig filterConfig = null;
	private boolean flag = true;
	private String charcode ="GBK";
	protected boolean igore = true;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain fc) throws IOException, ServletException {
		try{
		
		if(flag){
			String c = request.getCharacterEncoding();
			if(c==null){
				request.setCharacterEncoding(charcode);
			}else if(!c.equals(this.charcode)){
				request.setCharacterEncoding(charcode);
			}
		}
		fc.doFilter(request, response);
		return;
		
		}catch(Exception e){
			
		}
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;
		String temp = this.filterConfig.getInitParameter("enable");
		String str = this.filterConfig.getInitParameter("encoding");
		if(temp!=null){
			if(temp.equals(true)){
				this.flag=true;
			}else if(temp.equals("false")){
				this.flag=false;
			}else{
				this.flag=true;
			}
		}
		if(str!=null){
			this.charcode=str;
		}
	}
	
}
